package tt.lab.pmbok.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import tt.lab.pmbok.dto.InoutDTO;
import tt.lab.pmbok.dto.ProcessDTO;
import tt.lab.pmbok.dto.Tree;
import tt.lab.pmbok.model.Inout;
import tt.lab.pmbok.model.PmbokProcess;
import tt.lab.pmbok.model.ProcessInout;
import tt.lab.pmbok.service.InoutService;

@Controller
// 类似Struts的Action
public class InoutController {
	/**/
	@Resource(name = "inoutService")
	private InoutService inoutService; 

	@RequestMapping("/inouts")
	public void retrieveAll(Model model) {
		List<Inout> inouts = inoutService.loadAll();
		Tree rootNode = new Tree(0, "ROOT", "R", false, false);
		//List<InoutDTO> inoutDTOs = new ArrayList<InoutDTO>();
		for(Inout inout : inouts){
			//InoutDTO inoutDTO = new InoutDTO(inout.getId(),inout.getName());
			//inoutDTOs.add(inoutDTO);
			Tree inoutNode = new Tree(inout.getId()+100, inout.getName(), "I", false, true);
			rootNode.addChild(inoutNode);
		}
		model.addAttribute("children", rootNode.getChildren());
	}
	
	@RequestMapping("/inout/{id}")
	public void retrieve(@PathVariable int id, Model model) {
		Inout inout = inoutService.load(id);
		
		InoutDTO inoutDTO = new InoutDTO(inout.getId(),inout.getName());
		for(ProcessInout processInout : inout.getSortedProcesses()){
			PmbokProcess process = processInout.getProcess();
			ProcessDTO processDTO = new ProcessDTO(process.getId(), process.getName(), process.getPmbokId());
			if("I".equals(processInout.getType())){
				inoutDTO.addToProcess(processDTO);
			} else 	if("O".equals(processInout.getType())){
				inoutDTO.addFromProcess(processDTO);
			}
		}
		model.addAttribute("inout", inoutDTO);
	}

}